package com.sky.config;


import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {


    @Value("${sky.redis.host}")
    private String redisHost;

    @Value("${sky.redis.port}")
    private int redisPort;


    @Autowired
    private RedissonClient redissonClient;



    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress(String.format("redis://%s:%d", redisHost, redisPort));

        return Redisson.create(config);
    }
    //其实Spring Boot 框架会自动装配 RedisTemplate 对象，但我们为了设置其序列化器选择自己配置这么一个第三方Bean
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("开始创建redis模板对象...");
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
        //设置redis的连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置redis key的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }


    @Bean
    public RBloomFilter<String> bloomFilter() {
        // 定义一个布隆过滤器，指定布隆过滤器的名称
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("bloomFilter");
        //定义布隆过滤器的大小，以及误差率
        bloomFilter.tryInit(100000L, 0.003);
        return bloomFilter;
    }
}
